package com.huaiwei.usmManager.modules.sys.controller;

import com.huaiwei.usmManager.common.exception.RRException;
import com.huaiwei.usmManager.common.utils.Constant;
import com.huaiwei.usmManager.common.utils.PageUtils;
import com.huaiwei.usmManager.common.utils.R;
import com.huaiwei.usmManager.modules.sys.entity.SysUserEntity;
import com.huaiwei.usmManager.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/sys/user")
@Api(tags = "后台用户管理模块")
public class SysUserController extends AbstractController {

    @Autowired
    private SysUserService userService;

    @GetMapping("/info")
    @ApiOperation("获取当前登录用户信息")
    public R info(){
        return R.ok().put("user",getUser());
    }

    @GetMapping("/list")
    @ApiOperation("分页查询用户列表")
    public R list(@RequestParam Map<String,Object> params){
        PageUtils page= userService.getPageList(params);
        return R.ok().put("page",page);
    }

    @GetMapping("/info/{userId}")
    @ApiOperation("根据ID获取用户信息")
    public R info(@PathVariable("userId") Long userId){
        return R.ok().put("user",userService.getById(userId));
    }

    @PostMapping("/update")
    @ApiOperation("添加或修改用户信息")
    public R update(@RequestBody SysUserEntity user){
        if(user.getUserId()==null){
            user.setCreateId(getUserId());
        }
        userService.insertOrUpdate(user);
        return R.ok();
    }

    @PostMapping("/password")
    @ApiOperation("修改密码")
    public R updatePassword(String password,String newPassword){
        String rightPwd=getUser().getPassword();
        password=new Sha256Hash(password,getUser().getSalt()).toHex();
        if(rightPwd.equals(password)){
            newPassword=new Sha256Hash(newPassword,getUser().getSalt()).toHex();
            boolean flag= userService.updatePassword(getUserId(),password,newPassword);
            return flag?R.ok():R.error();
        }else{
            throw new RRException("原密码不正确！");
        }

    }

    @DeleteMapping("/delete/{userId}")
    public R delete(@PathVariable("userId") Long userId){
        if(userId == Constant.SUPER_ADMIN){
            return R.error("系统管理员不得删除");
        }
        if(userId.equals(getUserId())){
            return R.error("当前用户不能删除");
        }
        userService.removeById(userId);
        return  R.ok();
    }

}
